/**
 * Created by wangyazheng on 17/4/11.
 */
import React, {Component} from "react";
import {restApiRequest} from "../Public/Api/Public";
import {ListView, PullToRefresh, Toast} from "antd-mobile";

//每页显示数据的条数
const pageSize = 5;
let pageNum = 1;
let product_url = '/shop/api/topicList';
let ProductInfoList = [];
export default class HomePage extends Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      foot: 0,
      isRefreshing: false,
    };
  }

  componentWillMount() {
    // console.log(this.props.location.state, '----->this.props')
    ProductInfoList = [];
    pageNum = 1;

    let param = {page_num: pageNum, page_size: pageSize};
    let jsonData = restApiRequest.getSign(param);
    // let product_url = 'shop/api/majorlist';
    this.fetchProductListData(product_url, jsonData);
  }

  //获取商品列表
  fetchProductListData(url, jsonData) {
    restApiRequest.fetchp(url, jsonData).then((response) => {
      if (!response.ok) {
        var error = new Error(response.statusText);
        error.response = response;
        throw error;
      } else {
        return response.json();
      }
    }).then((response_json) => {
      console.log('productList--->', response_json);
      if (response_json.code === '0000') {
        let responseData = response_json.data;
        //请求结果有数据
        if (responseData.topic_list.length > 0) {
          //请求数据小于5数据加载完
          if (responseData.topic_list.length < pageSize) {
            //加载完毕
            this.setState({foot: 1});
          } else {
            //隐藏
            this.setState({foot: 0});
          }
          if (responseData.topic_list != null) {
            //每次请求结果push到商品列表数组进行渲染
            for (var i = 0; i < responseData.topic_list.length; i++) {
              ProductInfoList.push(responseData.topic_list[i]);
            }
            this.setState({
              dataSource: this.state.dataSource.cloneWithRows(ProductInfoList),
            });
          }
        } else {
          this.setState({foot: 1});
        }
        this.setState({isRefreshing: false})
      } else {
        return Toast.offline(response_json.msg, 2)
      }
    }).catch((ex) => {
      console.log(ex);
    });
  }

  //点击跳转详情
  jumpRow(rowData) {
    // console.log(rowData.id)
    window.location.href = "https://api.hidizhu.com/api/WebView/topic?is_wx=1&topic_id=" + rowData.id;
    // this.context.router.push({
    //   pathname: '/ProductDetail',
    //   state: rowData.id,
    // })
  }

  //下拉刷新
  onRefresh() {
    this.setState({isRefreshing: true});
    ProductInfoList = [];
    let param = {page_num: 1, page_size: pageSize};
    let jsonData = restApiRequest.getSign(param);
    // let product_url = 'shop/api/homeTopicList';
    this.fetchProductListData(product_url, jsonData);
  }

  //加载更多
  onEndReached() {
    if (this.state.foot != 0) {
      return;
    }
    this.setState({
      foot: 2,
    });
    pageNum++;
    console.log('当前页数:' + pageNum);
    let param = {page_num: pageNum, page_size: pageSize};
    let jsonData = restApiRequest.getSign(param);
    this.fetchProductListData(product_url, jsonData);
  }

  renderHeader() {
    return (
      <div style={{height: '.3rem'}}/>
    )
  }

  renderFooter() {
    if (this.state.foot === 0) {            //上滑加载更多
      return (
        <div className="hom-list-footer">
          <svg className="hom-list-footer-icon">
            <use xlinkHref='#icon-ico_page_bottom_dog'></use>
          </svg>
          <p
            className="hom-list-footer-text">往上滑加载更多...</p>
        </div>);
    } else if (this.state.foot === 1) {    //加载完毕
      return (
        <section className="hom-list-footer" style={{
          marginBottom: 0,
          paddingBottom: 0
        }}>
          <svg className="hom-list-footer-icon">
            <use xlinkHref={'#icon-ico_page_bottom_dog'}></use>
          </svg>
          <p className="hom-list-footer-text">我是有底线的</p>
        </section>);
    } else if (this.state.foot === 2) {     //加载中
      return (
        <div className="hom-list-footer">
          <svg className="hom-list-footer-icon">
            <use xlinkHref='#icon-ico_page_bottom_dog'></use>
          </svg>
          <p className="hom-list-footer-text">拼命加载中...</p>
        </div>);
    }
  }


  render() {
    const projectrenderList = (rowData, sectionID, rowID) => {
      return (
        <div className="home-TopicList-list"
             key={rowID}
             onClick={() => this.jumpRow(rowData)}>
          <img src={rowData.topic_cover_pic_url} className="home-TopicList-img"/>
        </div>
      )
    };
    return (
      <ListView ref='productList'
                dataSource={this.state.dataSource}
                initialListSize={4}
                renderRow={projectrenderList}
                scrollRenderAheadDistance={1000}
                scrollEventThrottle={20}
                style={{
                  height: window.innerHeight ,
                  overflow: 'auto',
                }}
                renderHeader={this.renderHeader.bind(this)}
                renderFooter={this.renderFooter.bind(this)}
                onEndReached={this.onEndReached.bind(this)}
                onEndReachedThreshold={10}
                pullToRefresh={
                    <PullToRefresh
                        refreshing={this.state.isRefreshing}
                        onRefresh={this.onRefresh.bind(this)}
                        indicator={{deactivate: '下拉'}}
                    />
                }
      />
    )
  }
}
